package com.woniuxy.tmssystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.woniu.tmscommons.entity.Menu;
import com.woniu.tmscommons.entity.RoleMenu;
import com.woniuxy.tmssystem.mapper.RoleMenuMapper;
import com.woniuxy.tmssystem.service.RoleMenuService;
import com.woniuxy.tmssystem.utils.MenuUtils;
import com.woniuxy.tmssystem.vo.RoleMenuVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
/**
 * @Author：田江涛
 * @Package：com.woniuxy.tmssystem.service.impl
 * @Project：TMS
 * @name：RoleMenuServiceImpl
 * @Date：2024/9/3 10:16
 * @Filename：RoleMenuServiceImpl
 * @Description:
 */
@Service
public class RoleMenuServiceImpl implements RoleMenuService {
    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Override
    public List<RoleMenuVo> getRoleMenu() {
        List<RoleMenuVo> roleMenuVo = roleMenuMapper.getRoleMenuVo();
        return MenuUtils.buildTree(roleMenuVo);
    }

    @Override
    public RoleMenuVo getRoleMenuByRoleId(Integer roleId) {
        RoleMenuVo roleMenuVo = roleMenuMapper.getRoleMenuVoByRoleId(roleId);
        List<Menu> menus = MenuUtils.buildMenuTree(roleMenuVo.getMenus());
        roleMenuVo.getMenus().addAll(menus);
        return roleMenuVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addRoleMenu(Integer roleId, List<Integer> menuIds) {
        boolean flag = true;
        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId).setMenuId(menuId);
            flag = roleMenuMapper.insert(roleMenu)>0;
        }
        return flag;
    }

    @Override
    public boolean addRoleMenu(Integer roleId, Integer menuId) {
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRoleId(roleId).setMenuId(menuId);
        return roleMenuMapper.insert(roleMenu)>0;
    }
    @Override
    public RoleMenu getRoleMenuByRoleIdAndMenuId(Integer roleId, Integer menuId) {
        LambdaQueryWrapper<RoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RoleMenu::getRoleId,roleId).eq(RoleMenu::getMenuId,menuId);
        return roleMenuMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public boolean deleteRoleMenuByRoleIdAndMenuId(Integer roleId, Integer menuId) {
        LambdaQueryWrapper<RoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RoleMenu::getRoleId,roleId).eq(RoleMenu::getMenuId,menuId);
        return roleMenuMapper.delete(lambdaQueryWrapper)>0;
    }
}
